//
//  YYComposeView.swift
//  YYWeibo
//
//  Created by strongwallyi on 16/1/4.
//  Copyright © 2016年 strongwallyi. All rights reserved.
//

import UIKit
import pop

class YYComposeView: UIView {
    
    //用于弱出控制器的目标控制器
    var target: UIViewController?

    lazy var childMenuButtons: [UIButton] = [UIButton]()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        frame.size = CGSizeMake(SCREENW, SCREENH)
        //获取一个磨砂的屏幕图片
        let imageView = UIImageView(image: UIImage.getScreenShot().applyLightEffect())
        //添加控件
        addSubview(imageView)
        addSubview(sloganImage)
        
        //添加约束
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self)
        }
        
        sloganImage.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(100)
        }
        
        addChildButton()
    }
    
    //添加子按钮
    private func addChildButton(){
        
        let childButtonW: CGFloat = 80
        let childButtonH: CGFloat = 110
        // 每一个按钮之间的间距
        let childButtonMargin: CGFloat = (SCREENW - 3 * childButtonW) / 4
        
        //获取文件路径
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
        //把 plist 文件转换成数组
        let composeMenuButtonInfo = NSArray(contentsOfFile: path)!
        
        for (i,value) in composeMenuButtonInfo.enumerate(){
            
            let button = YYComposeMenuButton()
            
            button.addTarget(self, action: "childButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            
            let dict = value as! NSDictionary
            
            let iconName = dict["icon"] as! String
            let title = dict["title"] as! String
            
            button.setImage(UIImage(named: iconName), forState: .Normal)
            button.setTitle(title, forState: .Normal)
            
            // 取到当前遍历的按钮的第 xx 行和 第 xx 列
            let col = i % 3
            let row = i / 3
            // 计算位置
            let childButtonX = CGFloat(col + 1) * childButtonMargin + CGFloat(col) * childButtonW
            let childButtonY = (childButtonH + childButtonMargin) * CGFloat(row) + SCREENH
            
            //设置 frame
            button.frame = CGRect(x: childButtonX, y: childButtonY, width: childButtonW, height: childButtonH)
            
            addSubview(button)
            
            childMenuButtons.append(button)
        }
    }
    
    //调用这个方法展示当前 view
    func show(target: UIViewController) {
        self.target = target
        self.target?.view.addSubview(self)
    }
    
    //按钮的点击事件
    @objc private func childButtonClick(button: UIButton) {
        //点击的按钮放大透明
        //没有点击的按钮缩小透明
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            for value in self.childMenuButtons {
                value.alpha = 0.01
                if value == button {
                    value.transform = CGAffineTransformMakeTranslation(2, 2)
                }else{
                    value.transform = CGAffineTransformMakeTranslation(0.2, 0.2)
                }
            }
        }) { (_) -> Void in
            
            if let type = NSClassFromString("YYWeibo.YYComposeViewController") as? UIViewController.Type{
                let instance = type.init()
                //点击之后弹出控制器
                self.target?.presentViewController(YYNavigationController(rootViewController:instance), animated: true, completion: { () -> Void in
                    self.removeFromSuperview()
                })
            }
        }
    }
    
    //当前控件移动到 window 上执行的方法
    override func didMoveToWindow() {
        for (index,button) in childMenuButtons.enumerate(){
        doAnimation(button, index: index, isUp: true)
        }
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        //将当前控件从父控件上移除
        //reverse反转的意思,将数组进行倒着遍历
        for (index,button) in childMenuButtons.reverse().enumerate(){
            doAnimation(button, index: index)
        }
        //从父控件中移除
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.4 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {
            self.removeFromSuperview()
        }
    }
    
    //执行动画
    private func doAnimation(button: UIButton, index: Int, isUp: Bool = false){
        //执行动画
        let animation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        
        var y = button.center.y + 350
        
        if isUp {
            y = button.center.y - 350
        }
        
        animation.toValue = NSValue(CGPoint: CGPoint(x: button.center.x, y: y))
        //弹性度
        animation.springBounciness = 10
        //弹性速度
        animation.springSpeed = 8
        //当前系统的绝对时间,每次间隔多少秒之后后面的按钮开始动画
        animation.beginTime = CACurrentMediaTime() + Double(index) * 0.025
        //添加动画
        button.pop_addAnimation(animation, forKey: nil)
    }
    
    //MARK: -- 懒加载控件
    private lazy var sloganImage: UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))
    
}
